package com.lky.marshall.mallcart.controller;

import com.lky.marshall.mallcart.interceptor.CartInterceptor;
import com.lky.marshall.mallcart.service.CartService;
import com.lky.marshall.mallcart.vo.CartItemVo;
import com.lky.marshall.mallcart.vo.CartVo;
import com.lky.marshall.mallcart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Created by
 * autor : Marshall lky
 * datetime: 2021/6/1 10:43
 */
@Controller
public class CartController {

    @Autowired
    private CartService cartService;


    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {
//        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
//        System.out.println(userInfoTo);
        CartVo cartVo = cartService.getCart();
        model.addAttribute("cartVo",cartVo);
        return "cartList";
    }

    @GetMapping("/addToCart")
    public String addToCart(Long skuId, Integer num, RedirectAttributes ra) throws ExecutionException, InterruptedException {

        CartItemVo cartItemVo = cartService.addToCart(skuId, num);

        ra.addAttribute("skuId", skuId);
        return "redirect:http://cart.marshallmall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccessPage(@RequestParam("skuId") Long skuId, Model model) {
        //重定向到页面，再次查询购物车数据
        CartItemVo cartItemVo = cartService.getCartItem(skuId);
        model.addAttribute("cart",cartItemVo);
        return "success";
    }

    @GetMapping("/currentUserCartItems")
    @ResponseBody
    public List<CartItemVo> getCurrentUserCartItems(){
        return cartService.getCurrentUserCartItems();
    }


}
